Handling multiple statements and transaction
https://gyazo.com/ed6df50c3b2e854f351aa2a1327e18ad #Core
Handling multiple statement
org.nkjmlab.sorm4j.Sorm handling a OrmConnection with a handler. Sorm applies the handler via accept or applymethod. java.sql.Connection will be closed after executing accept or apply. These methods are suitable for executing multiple SQL statements at getting Connection at once.
OrmConnection wraps an active database javax.sql.Connection. The connection will be closed after the process of handler.
If your operation will return some result, use Sorm#applyHandler():
code:java
Customer c1 = sorm.applyHandler(conn -> {
conn.insert(new Customer(0));
conn.readFirst(Customer.class, "select * from customer");
});
If your operation does not need to return a result, use Sorm#acceptHandler():
code:java
sorm.acceptHandler(conn -> {
conn.exeuteUpdate(CREATE TABLE customer (id INT PRIMARY KEY, name VARCHAR, address VARCHAR));
conn.insert(new Customer(0));
conn.insert(new Customer(1));
});
Transaction
Lambda expression
Sorm#acceptHandler(int, FunctionHandler) and Sorm#acceptHandler(int, FunctionHandler) methods could handle transactions. The transaction will be rollback after the process of the handler. When the transaction throws an exception, the transaction will be also rollback.
code:java
// Transaction with lambda expression
// The inserted row will be not persisted.
sorm.acceptHandler(Connection.TRANSACTION_READ_COMMITTED, trans -> trans.insert(Customer.ALICE));
// The inserted row will be persisted.
sorm.acceptHandler(Connection.TRANSACTION_READ_COMMITTED, trans -> {
trans.insert(Customer.ALICE);
trans.commit();
});
Try-with-resources
Orm#open method open a transaction. The transaction is automatically rollback when closing the OrmTransaction.
code:java
// Transaction with try-with-resources block. In this way transaction is auto rollback.
try (OrmTransaction trans = sorm.open(Connection.TRANSACTION_READ_COMMITTED)) {
trans.readOne(Integer.class, "select count(*) from customer");
// If the transaction is not committed, it will be automatically rollback when closing the OrmTransaction
trans.insert(Customer.CAROL);
}